import React, {
	Component,
	PropTypes
} from 'react'
import ArticleItem from './ArticleItem.js'
import {
	fetchArticle,
	fetchArticleByPage
} from './articleAction.js'

var counter = 0

class ArticleLists extends Component {
	// constructor(props) {
	// 	super(props)
	// 	this.counter = 0
	// }
	nextPage() {
		// console.log(this.counter)
		return counter += 10
	}

	// 首屏加载
	componentDidMount() {
		const {
			dispatch
		} = this.props

		window.addEventListener('scroll', this.handleScroll.bind(this))

		dispatch(fetchArticleByPage())
	}

	// componentWillUnmount() {
	// 	window.removeEventListener('scroll', this.handleScroll.bind(this));
	// }
	handleScroll() {
		const {
			dispatch
		} = this.props
		var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
		var scrollHeight = document.body.scrollHeight;
		var screenHeight = window.screen.height;
		var limit = (scrollTop + screenHeight) / scrollHeight
		if (limit >= 1) {
			// 瀑布流加载
			dispatch(fetchArticleByPage(this.nextPage()))
		}
	}
	handleClick() {
		const {
			dispatch
		} = this.props
		dispatch(fetchArticleByPage(this.counter))
	}
	render() {
		return (
			<div>
				{
					Array.prototype.map.call(this.props.lists,(elem, index) => {
						return <ArticleItem article={elem} key={index}/>
					})
				}	
				<button onClick={this.handleClick.bind(this)}>Refresh</button>
			</div>
		)
	}
}

ArticleLists.defaultProps = {
	lists: []
}

export default ArticleLists